<template>
  <!-- 宠物论坛页顶部条 -->
  <div style="height:6vh;padding: 10px 20px;background-color:#fff;">
    <span style="line-height: 60px;font-size:20px;">宠物论坛</span>
    <el-button type="primary" style="float:right;margin-top: 10px;" @click="beforeAddPost">发布新帖</el-button>
  </div>
  <!-- 发布/编辑帖子弹窗 -->
  <el-dialog
      :title="dialogTitle"
      style="width: 800px; padding: 40px;"
      v-model="dialogVisible"
      :before-close="handleClose"
  >
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="帖子标题">
            <el-input
                placeholder="请输入帖子标题"
                v-model="savePostForm.title"
                :rules="[
                { required: true, message: '请输入帖子标题', trigger: 'blur' },
                { max: 50, message: '标题长度不能超过50个字符', trigger: 'blur' }
              ]"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发布者">
            <el-input
                placeholder="请输入发布者用户名"
                v-model="savePostForm.publisher"
                :rules="[
                { required: true, message: '请输入发布者', trigger: 'blur' },
                { max: 50, message: '发布者名称长度不能超过50个字符', trigger: 'blur' }
              ]"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="帖子内容">
            <el-input
                type="textarea"
                placeholder="请输入帖子内容"
                v-model="savePostForm.content"
                :rules="[
                { required: true, message: '请输入帖子内容', trigger: 'blur' },
                { max: 2000, message: '内容长度不能超过2000个字符', trigger: 'blur' }
              ]"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="帖子状态">
            <el-select
                placeholder="请选择"
                v-model="savePostForm.status"
                :rules="{ required: true, message: '请选择帖子状态', trigger: 'change' }"
            >
              <el-option label="正常" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="savePost">保存</el-button>
    </template>
  </el-dialog>

  <!-- 帖子搜索卡片 -->
  <el-card style="height: 70px;margin: 20px;">
    <el-form :inline="true">
      <el-form-item label="帖子搜索" style="width: 220px;">
        <el-input placeholder="输入帖子标题" v-model="searchPostForm.title" @keydown.enter="loadPosts"></el-input>
      </el-form-item>
      <el-form-item label="发布者" style="width: 220px;">
        <el-input placeholder="输入发布者用户名" v-model="searchPostForm.publisher" @keydown.enter="loadPosts"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadPosts">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 帖子列表 -->
  <el-card style="margin: 20px;">
    <el-table :data="postArr" stripe>
      <el-table-column type="index" label="编号" width="80" align="center"></el-table-column>
      <el-table-column label="帖子标题" prop="title" align="center"></el-table-column>
      <el-table-column label="帖子内容" prop="content" align="center"></el-table-column>
      <el-table-column label="发布者" prop="publisher" align="center"></el-table-column>
      <el-table-column label="帖子状态" prop="status" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="editPost(scope.row.id)">编辑</el-button>
          <el-button link type="primary" @click="deletePost(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalPosts"
    ></el-pagination>
  </el-card>
</template>

<script setup>
import {onMounted, ref, reactive} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";



// 定义变量用来控制弹窗是否可见
const dialogVisible = ref(false);
// 定义对象用来收集帖子表单数据
const savePostForm = ref({
  id: null,
  title: '',
  content: '',
  publisher: '',
  status: null
});
// 定义变量用来保存帖子搜索条件
const searchPostForm = ref({
  title: '',
  publisher: ''
});
// 定义数组用来保存帖子列表数据
const postArr = ref([]);
// 分页相关
const currentPage = ref(1);
const pageSize = ref(5);
const totalPosts = ref(0);
// 定义变量用来保存弹窗的标题
const dialogTitle = ref('发布新帖');

// 定义点击"发布新帖"按钮时调用的方法
const beforeAddPost = () => {
  dialogTitle.value = '发布新帖';
  dialogVisible.value = true;
  savePostForm.value.id = null;
  savePostForm.value.title = '';
  savePostForm.value.content = '';
  savePostForm.value.publisher = '';
  savePostForm.value.status = null;
}
// 定义保存帖子的方法
const savePost = () => {
  let data = qs.stringify(savePostForm.value);
  console.log(data);
  axios.post(BASE_URL + '/v1/post/save', data).then((response) => {
    if (response.data.code === 2000) {
      ElMessage.success('保存成功!');
      savePostForm.value = {}; // 保存成功后要清空弹窗表单并关闭弹窗
      dialogVisible.value = false;
      // 新增成功后，需要重新加载所有的宠物用户数据
      loadPosts();
    } else {
      ElMessage.error(response.data.msg);
    }
  })
}
// 定义处理弹窗关闭的方法
const handleClose = () => {
  if (confirm('您确认要关闭弹窗吗?')) {
    savePostForm.value = {};
    dialogVisible.value = false;
  }
}
// 定义加载帖子列表的方法
const loadPosts = () => {
  console.log(searchPostForm.value);
  let data = qs.stringify(searchPostForm.value);
  axios.get(BASE_URL + '/v1/post/select?' + data).then((response) => {
    if (response.data.code === 2000) {
      postArr.value = response.data.data;
      console.log(postArr.value);
    } else {
      ElMessage.error(response.data.msg);
    }
  })
}
// 页面加载完毕立即调用加载帖子的方法
onMounted(() => {
  loadPosts();
})
// 定义重置搜索的方法
const resetSearch = () => {
  searchPostForm.value = {};
  loadPosts();
}
// 定义编辑帖子的方法
const editPost = (id) => {
  dialogVisible.value = true;
  dialogTitle.value = '编辑帖子';
  axios.get(BASE_URL + '/v1/post/select?id=' + id).then((response) => {
    if (response.data.code === 2000) {
      savePostForm.value = response.data.data[0];
    } else {
      ElMessage.error(response.data.msg);
    }
  })
}
// 定义删除帖子的方法
const deletePost = (id) => {
  if (confirm('您确认要删除当前帖子吗?')) {
    axios.post(BASE_URL + '/v1/post/delete/' + id).then((response) => {
      if (response.data.code === 2000) {
        ElMessage.success('帖子删除成功!');
        loadPosts();
      } else {
        ElMessage.error(response.data.msg);
      }
    })
  }
}
// 处理每页数量变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  loadPosts();
}
// 处理当前页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  loadPosts();
}
</script>

<style scoped>
/* 可根据需要添加样式 */
</style>